<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/examples/simpletreemodel.qdoc -->
<head>
  <title>Qt 4.3: Simple Tree Model Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Simple Tree Model Example<br /><small></small></h1>
<p>Files:</p>
<ul>
<li><a href="itemviews-simpletreemodel-treeitem-cpp.html">itemviews/simpletreemodel/treeitem.cpp</a></li>
<li><a href="itemviews-simpletreemodel-treeitem-h.html">itemviews/simpletreemodel/treeitem.h</a></li>
<li><a href="itemviews-simpletreemodel-treemodel-cpp.html">itemviews/simpletreemodel/treemodel.cpp</a></li>
<li><a href="itemviews-simpletreemodel-treemodel-h.html">itemviews/simpletreemodel/treemodel.h</a></li>
<li><a href="itemviews-simpletreemodel-main-cpp.html">itemviews/simpletreemodel/main.cpp</a></li>
<li><a href="itemviews-simpletreemodel-simpletreemodel-qrc.html">itemviews/simpletreemodel/simpletreemodel.qrc</a></li>
</ul>
<p>The Simple Tree Model example shows how to create a basic, read-only hierarchical model to use with Qt's standard view classes. For a description of simple non-hierarchical list and table models, see the <a href="model-view-programming.html">Model/View Programming</a> overview.</p>
<p align="center"><img src="images/simpletreemodel-example.png" /></p><p>Qt's model/view architecture provides a standard way for views to manipulate information in a data source, using an abstract model of the data to simplify and standardize the way it is accessed. Simple models represent data as a table of items, and allow views to access this data via an <a href="model-view-model.html">index-based</a> system. More generally, models can be used to represent data in the form of a tree structure by allowing each item to act as a parent to a table of child items.</p>
<p>Before attempting to implement a tree model, it is worth considering whether the data is supplied by an external source, or whether it is going to be maintained within the model itself. In this example, we will implement an internal structure to hold data rather than discuss how to package data from an external source.</p>
<a name="design-and-concepts"></a>
<h2>Design and Concepts</h2>
<p>The data structure that we use to represent the structure of the data takes the form of a tree built from <tt>TreeItem</tt> objects. Each <tt>TreeItem</tt> represents an item in a tree view, and contains several columns of data.</p>
<a name="simpletreemodelstructure"></a><p><table align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><img src="images/treemodel-structure.png" /></td><td><b>Simple Tree Model Structure</b><p>The data is stored internally in the model using <tt>TreeItem</tt> objects that are linked together in a pointer-based tree structure. Generally, each <tt>TreeItem</tt> has a parent item, and can have a number of child items. However, the root item in the tree structure has no parent item and it is never referenced outside the model.</p>
<p>Each <tt>TreeItem</tt> contains information about its place in the tree structure; it can return its parent item and its row number. Having this information readily available makes implementing the model easier.</p>
<p>Since each item in a tree view usually contains several columns of data (a title and a summary in this example), it is natural to store this information in each item. For simplicity, we will use a list of <a href="qvariant.html">QVariant</a> objects to store the data for each column in the item.</p>
</td></tr>
</table></p>
<p>The use of a pointer-based tree structure means that, when passing a model index to a view, we can record the address of the corresponding item in the index (see <a href="qabstractitemmodel.html#createIndex">QAbstractItemModel::createIndex</a>()) and retrieve it later with <a href="qmodelindex.html#internalPointer">QModelIndex::internalPointer</a>(). This makes writing the model easier and ensures that all model indexes that refer to the same item have the same internal data pointer.</p>
<p>With the appropriate data structure in place, we can create a tree model with a minimal amount of extra code to supply model indexes and data to other components.</p>
<a name="treeitem-class-definition"></a>
<h2>TreeItem Class Definition</h2>
<p>The <tt>TreeItem</tt> class is defined as follows:</p>
<pre> class TreeItem
 {
 public:
     TreeItem(const QList&lt;QVariant&gt; &amp;data, TreeItem *parent = 0);
     ~TreeItem();

     void appendChild(TreeItem *child);

     TreeItem *child(int row);
     int childCount() const;
     int columnCount() const;
     QVariant data(int column) const;
     int row() const;
     TreeItem *parent();

 private:
     QList&lt;TreeItem*&gt; childItems;
     QList&lt;QVariant&gt; itemData;
     TreeItem *parentItem;
 };</pre>
<p>The class is a basic C++ class. It does not inherit from <a href="qobject.html">QObject</a> or provide signals and slots. It is used to hold a list of QVariants, containing column data, and information about its position in the tree structure. The functions provide the following features:</p>
<ul>
<li>The <tt>appendChildItem()</tt> is used to add data when the model is first constructed and is not used during normal use.</li>
<li>The <tt>child()</tt> and <tt>childCount()</tt> functions allow the model to obtain information about any child items.</li>
<li>Information about the number of columns associated with the item is provided by <tt>columnCount()</tt>, and the data in each column can be obtained with the data() function.</li>
<li>The <tt>row()</tt> and <tt>parent()</tt> functions are used to obtain the item's row number and parent item.</li>
</ul>
<p>The parent item and column data are stored in the <tt>parentItem</tt> and <tt>itemData</tt> private member variables. The <tt>childItems</tt> variable contains a list of pointers to the item's own child items.</p>
<a name="treeitem-class-implementation"></a>
<h2>TreeItem Class Implementation</h2>
<p>The constructor is only used to record the item's parent and the data associated with each column.</p>
<pre> TreeItem::TreeItem(const QList&lt;QVariant&gt; &amp;data, TreeItem *parent)
 {
     parentItem = parent;
     itemData = data;
 }</pre>
<p>A pointer to each of the child items belonging to this item will be stored in the <tt>childItems</tt> private member variable. When the class's destructor is called, it must delete each of these to ensure that their memory is reused:</p>
<pre> TreeItem::~TreeItem()
 {
     qDeleteAll(childItems);
 }</pre>
<p>Since each of the child items are constructed when the model is initially populated with data, the function to add child items is straightforward:</p>
<pre> void TreeItem::appendChild(TreeItem *item)
 {
     childItems.append(item);
 }</pre>
<p>Each item is able to return any of its child items when given a suitable row number. For example, in the <a href="#simpletreemodelstructure">above diagram</a>, the item marked with the letter &quot;A&quot; corresponds to the child of the root item with <tt>row = 0</tt>, the &quot;B&quot; item is a child of the &quot;A&quot; item with <tt>row = 1</tt>, and the &quot;C&quot; item is a child of the root item with <tt>row = 1</tt>.</p>
<p>The <tt>child()</tt> function returns the child that corresponds to the specified row number in the item's list of child items:</p>
<pre> TreeItem *TreeItem::child(int row)
 {
     return childItems.value(row);
 }</pre>
<p>The number of child items held can be found with <tt>childCount()</tt>:</p>
<pre> int TreeItem::childCount() const
 {
     return childItems.count();
 }</pre>
<p>The <tt>TreeModel</tt> uses this function to determine the number of rows that exist for a given parent item.</p>
<p>The <tt>row()</tt> function reports the item's location within its parent's list of items:</p>
<pre> int TreeItem::row() const
 {
     if (parentItem)
         return parentItem-&gt;childItems.indexOf(const_cast&lt;TreeItem*&gt;(this));

     return 0;
 }</pre>
<p>Note that, although the root item (with no parent item) is automatically assigned a row number of 0, this information is never used by the model.</p>
<p>The number of columns of data in the item is trivially returned by the <tt>columnCount()</tt> function.</p>
<pre> int TreeItem::columnCount() const
 {
     return itemData.count();
 }</pre>
<p>Column data is returned by the <tt>data()</tt> function, taking advantage of <a href="qlist.html">QList</a>'s ability to provide sensible default values if the column number is out of range:</p>
<pre> QVariant TreeItem::data(int column) const
 {
     return itemData.value(column);
 }</pre>
<p>The item's parent is found with <tt>parent()</tt>:</p>
<pre> TreeItem *TreeItem::parent()
 {
     return parentItem;
 }</pre>
<p>Note that, since the root item in the model will not have a parent, this function will return zero in that case. We need to ensure that the model handles this case correctly when we implement the <tt>TreeModel::parent()</tt> function.</p>
<a name="treemodel-class-definition"></a>
<h2>TreeModel Class Definition</h2>
<p>The <tt>TreeModel</tt> class is defined as follows:</p>
<pre> class TreeModel : public QAbstractItemModel
 {
     Q_OBJECT

 public:
     TreeModel(const QString &amp;data, QObject *parent = 0);
     ~TreeModel();

     QVariant data(const QModelIndex &amp;index, int role) const;
     Qt::ItemFlags flags(const QModelIndex &amp;index) const;
     QVariant headerData(int section, Qt::Orientation orientation,
                         int role = Qt::DisplayRole) const;
     QModelIndex index(int row, int column,
                       const QModelIndex &amp;parent = QModelIndex()) const;
     QModelIndex parent(const QModelIndex &amp;index) const;
     int rowCount(const QModelIndex &amp;parent = QModelIndex()) const;
     int columnCount(const QModelIndex &amp;parent = QModelIndex()) const;

 private:
     void setupModelData(const QStringList &amp;lines, TreeItem *parent);

     TreeItem *rootItem;
 };</pre>
<p>This class is similar to most other subclasses of <a href="qabstractitemmodel.html">QAbstractItemModel</a> that provide read-only models. Only the form of the constructor and the <tt>setupModelData()</tt> function are specific to this model. In addition, we provide a destructor to clean up when the model is destroyed.</p>
<a name="treemodel-class-implementation"></a>
<h2>TreeModel Class Implementation</h2>
<p>For simplicity, the model does not allow its data to be edited. As a result, the constructor takes an argument containing the data that the model will share with views and delegates:</p>
<pre> TreeModel::TreeModel(const QString &amp;data, QObject *parent)
     : QAbstractItemModel(parent)
 {
     QList&lt;QVariant&gt; rootData;
     rootData &lt;&lt; &quot;Title&quot; &lt;&lt; &quot;Summary&quot;;
     rootItem = new TreeItem(rootData);
     setupModelData(data.split(QString(&quot;\n&quot;)), rootItem);
 }</pre>
<p>It is up to the constructor to create a root item for the model. This item only contains vertical header data for convenience. We also use it to reference the internal data structure that contains the model data, and it is used to represent an imaginary parent of top-level items in the model.</p>
<p>The model's internal data structure is populated with items by the <tt>setupModelData()</tt> function. We will examine this function separately at the end of this document.</p>
<p>The destructor ensures that the root item and all of its descendants are deleted when the model is destroyed:</p>
<pre> TreeModel::~TreeModel()
 {
     delete rootItem;
 }</pre>
<p>Since we cannot add data to the model after it is constructed and set up, this simplifies the way that the internal tree of items is managed.</p>
<p>Models must implement an <tt>index()</tt> function to provide indexes for views and delegates to use when accessing data. Indexes are created for other components when they are referenced by their row and column numbers, and their parent model index. If an invalid model index is specified as the parent, it is up to the model to return an index that corresponds to a top-level item in the model.</p>
<p>When supplied with a model index, we first check whether it is valid. If it is not, we assume that a top-level item is being referred to; otherwise, we obtain the data pointer from the model index with its <a href="qmodelindex.html#internalPointer">internalPointer()</a> function and use it to reference a <tt>TreeItem</tt> object. Note that all the model indexes that we construct will contain a pointer to an existing <tt>TreeItem</tt>, so we can guarantee that any valid model indexes that we receive will contain a valid data pointer.</p>
<pre> QModelIndex TreeModel::index(int row, int column, const QModelIndex &amp;parent)
             const
 {
     if (!hasIndex(row, column, parent))
         return QModelIndex();

     TreeItem *parentItem;

     if (!parent.isValid())
         parentItem = rootItem;
     else
         parentItem = static_cast&lt;TreeItem*&gt;(parent.internalPointer());

     TreeItem *childItem = parentItem-&gt;child(row);
     if (childItem)
         return createIndex(row, column, childItem);
     else
         return QModelIndex();
 }</pre>
<p>Since the row and column arguments to this function refer to a child item of the corresponding parent item, we obtain the item using the <tt>TreeItem::child()</tt> function. The <a href="qabstractitemmodel.html#createIndex">createIndex()</a> function is used to create a model index to be returned. We specify the row and column numbers, and a pointer to the item itself. The model index can be used later to obtain the item's data.</p>
<p>The way that the <tt>TreeItem</tt> objects are defined makes writing the <tt>parent()</tt> function easy:</p>
<pre> QModelIndex TreeModel::parent(const QModelIndex &amp;index) const
 {
     if (!index.isValid())
         return QModelIndex();

     TreeItem *childItem = static_cast&lt;TreeItem*&gt;(index.internalPointer());
     TreeItem *parentItem = childItem-&gt;parent();

     if (parentItem == rootItem)
         return QModelIndex();

     return createIndex(parentItem-&gt;row(), 0, parentItem);
 }</pre>
<p>We only need to ensure that we never return a model index corresponding to the root item. To be consistent with the way that the <tt>index()</tt> function is implemented, we return an invalid model index for the parent of any top-level items in the model.</p>
<p>When creating a model index to return, we must specify the row and column numbers of the parent item within its own parent. We can easily discover the row number with the <tt>TreeItem::row()</tt> function, but we follow a convention of specifying 0 as the column number of the parent. The model index is created with <a href="qabstractitemmodel.html#createIndex">createIndex()</a> in the same way as in the <tt>index()</tt> function.</p>
<p>The <tt>rowCount()</tt> function simply returns the number of child items for the <tt>TreeItem</tt> that corresponds to a given model index, or the number of top-level items if an invalid index is specified:</p>
<pre> int TreeModel::rowCount(const QModelIndex &amp;parent) const
 {
     TreeItem *parentItem;
     if (parent.column() &gt; 0)
         return 0;

     if (!parent.isValid())
         parentItem = rootItem;
     else
         parentItem = static_cast&lt;TreeItem*&gt;(parent.internalPointer());

     return parentItem-&gt;childCount();
 }</pre>
<p>Since each item manages its own column data, the <tt>columnCount()</tt> function has to call the item's own <tt>columnCount()</tt> function to determine how many columns are present for a given model index. As with the <tt>rowCount()</tt> function, if an invalid model index is specified, the number of columns returned is determined from the root item:</p>
<pre> int TreeModel::columnCount(const QModelIndex &amp;parent) const
 {
     if (parent.isValid())
         return static_cast&lt;TreeItem*&gt;(parent.internalPointer())-&gt;columnCount();
     else
         return rootItem-&gt;columnCount();
 }</pre>
<p>Data is obtained from the model via <tt>data()</tt>. Since the item manages its own columns, we need to use the column number to retrieve the data with the <tt>TreeItem::data()</tt> function:</p>
<pre> QVariant TreeModel::data(const QModelIndex &amp;index, int role) const
 {
     if (!index.isValid())
         return QVariant();

     if (role != Qt::DisplayRole)
         return QVariant();

     TreeItem *item = static_cast&lt;TreeItem*&gt;(index.internalPointer());

     return item-&gt;data(index.column());
 }</pre>
<p>Note that we only support the <a href="qt.html#ItemDataRole-enum">DisplayRole</a> in this implementation, and we also return invalid <a href="qvariant.html">QVariant</a> objects for invalid model indexes.</p>
<p>We use the <tt>flags()</tt> function to ensure that views know that the model is read-only:</p>
<pre> Qt::ItemFlags TreeModel::flags(const QModelIndex &amp;index) const
 {
     if (!index.isValid())
         return 0;

     return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
 }</pre>
<p>The <tt>headerData()</tt> function returns data that we conveniently stored in the root item:</p>
<pre> QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
                                int role) const
 {
     if (orientation == Qt::Horizontal &amp;&amp; role == Qt::DisplayRole)
         return rootItem-&gt;data(section);

     return QVariant();
 }</pre>
<p>This information could have been supplied in a different way: either specified in the constructor, or hard coded into the <tt>headerData()</tt> function.</p>
<a name="setting-up-the-data-in-the-model"></a>
<h2>Setting Up the Data in the Model</h2>
<p>We use the <tt>setupModelData()</tt> function to set up the initial data in the model. This function parses a text file, extracting strings of text to use in the model, and creates item objects that record both the data and the overall model structure. Naturally, this function works in a way that is very specific to this model. We provide the following description of its behavior, and refer the reader to the example code itself for more information.</p>
<p>We begin with a text file in the following format:</p>
<pre> Getting Started                         How to familiarize yourself with Qt Designer
     Launching Designer                  Running the Qt Designer application
     The User Interface                  How to interact with Qt Designer
     ...</pre>
<pre> Connection Editing Mode                 Connecting widgets together with signals and slots
     Connecting Objects                  Making connections in Qt Designer
     Editing Connections                 Changing existing connections</pre>
<p>We process the text file with the following two rules:</p>
<ul>
<li>For each pair of strings on each line, create an item (or node) in a tree structure, and place each string in a column of data in the item.</li>
<li>When the first string on a line is indented with respect to the first string on the previous line, make the item a child of the previous item created.</li>
</ul>
<p>To ensure that the model works correctly, it is only necessary to create instances of <tt>TreeItem</tt> with the correct data and parent item.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
